using System.Web.Mvc;
using Headspring.Training.Core.Model;
using Headspring.Training.Core.Services;
using Headspring.Training.UI.Models;
using MvcContrib;

namespace Headspring.Training.UI.Controllers
{
	public class LoginController : Controller
	{
		private readonly IAuthenticationService _authenticationService;
		private readonly IEmployeeRepository _employeeRepository;
		private readonly IUserSession _userSession;

		public LoginController(IEmployeeRepository employeeRepository,
		                       IAuthenticationService authenticationService,
		                       IUserSession userSession)
		{
			_employeeRepository = employeeRepository;
			_authenticationService = authenticationService;
			_userSession = userSession;
		}

		public ViewResult Index()
		{
			Employee[] employees = _employeeRepository.GetAllEmployeesSorted();

			ViewData.Add(new EmployeeSelectList(employees));
			return View();
		}

		public ActionResult LogIn(string userName, string password)
		{
			Employee employee = _employeeRepository.GetByUserName(userName);

			bool passwordMatches = _authenticationService.PasswordMatches(employee,
			                                                              password);

			if (passwordMatches)
			{
				_userSession.LogIn(employee);
				return RedirectToAction("list", "search");
			}

			_userSession.PushUserMessage(
				new FlashMessage(FlashMessage.MessageType.Error, "Login incorrect"));
			return RedirectToAction("index");
		}

		public void LogOut()
		{
			_userSession.LogOut();
		}
	}
}